package com.hqbzl.c1;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class TestSleepAndNotify2 {
    static final Object room = new Object();
    static boolean hasCigarette = false;
    static boolean hasEat = false;

    public static void sleep(long t) {
        try {
            TimeUnit.SECONDS.sleep(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (room) {
                log.debug("外卖到没? {}", hasCigarette);
                if (!hasEat) {
                    log.debug("外卖没到-先歇会");
                    try {
                        room.wait(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("外卖没到? {}", hasEat);
                if (hasEat) {
                    log.debug("可以开始干活了");
                } else {
                    log.debug("没干成活");
                }
            }
        }, "小女").start();
        new Thread(() -> {
            synchronized (room) {
                log.debug("有烟没? {}", hasCigarette);
                if (!hasCigarette) {
                    log.debug("没烟-先歇会");
                    try {
                        room.wait(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("有烟没? {}", hasCigarette);
                if (hasCigarette) {
                    log.debug("可以开始干活了");
                } else {
                    log.debug("没干成活");
                }
            }
        }, "小南").start();


        sleep(1);
        new Thread(() -> {
            synchronized (room) {
                hasCigarette = true;
                log.debug("烟到了");
                // 错误唤醒
//              room.notify();
                // 错误唤醒
                room.notifyAll();
            }
        }, "送烟的").start();
    }
}
